//
//  MusicListViewController.m
//  哎游
//
//  Created by 康守帅 on 14-12-31.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "MusicListViewController.h"
#import "UIImageView+WebCache.h"
#import "ConnectModel.h"
#import "macro.h"
#import "MusicListModel.h"
#import "MusicListCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "UIScrollView+MJRefresh.h"
#import "MusicDetailViewController.h"

@interface MusicListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>

@end

@implementation MusicListViewController

- (void)dealloc
{
    [_collectionView release];
    [_collectionArray release];
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.collectionArray = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.page = 2;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 45, 60)];
    label.font = [UIFont fontWithName:@"TimesNewRomanPS-BoldMT" size:20];
    label.text = @"音乐";
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    
    [self startJson];
    [self createCollectionView];
    [self SetUpRefresh];
}

- (void)startJson
{
    NSString *str = @"http://mobile.ximalaya.com/m/explore_album_list?category_name=music&condition=hot&device=iPhone&page=1&per_page=20&status=0&tag_name=%E5%8D%8E%E8%AF%AD%7C%E7%B2%A4%E8%AF%AD";
//    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ConnectModel connectModelWithUrlStr:str parmaters:nil finished:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *array = [dic objectForKey:@"list"];
        for (NSDictionary *dic1 in array) {
            NSNumber *ID = [dic1 objectForKey:@"id"];
            MusicListModel *model = [[MusicListModel alloc] init];
            model.ID = ID;
            [model setValuesForKeysWithDictionary:dic1];
            [self.collectionArray addObject:model];
            [model release];
        }
        [_collectionView reloadData];
    }];

}

- (void)createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    [layout setItemSize:CGSizeMake((SCREEN_WIDTH - 10) / 2 , (SCREEN_WIDTH - 10) / 2 + 10)];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(5, 5, self.view.frame.size.width - 10, self.view.frame.size.height - 118) collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[MusicListCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionView];
    [_collectionView release];
    [layout release];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [_collectionArray count];;
}

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    return CGSizeMake(300, 50);
//}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MusicListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    MusicListModel *model = [_collectionArray objectAtIndex:indexPath.item];
    
    [cell.albumImageView sd_setImageWithURL:[NSURL URLWithString:model.albumCoverUrl290] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
    cell.name.text = model.title;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDetailViewController *music = [[MusicDetailViewController alloc] init];
    MusicListModel *model = [_collectionArray objectAtIndex:indexPath.item];
    music.ID = model.ID;
    music.name = model.title;
    music.playCounts = model.playCounts;
    [self.navigationController pushViewController:music animated:YES];
    [music release];
}

// 上拉加载, 下拉刷新
- (void)SetUpRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.collectionView addHeaderWithTarget:self action:@selector(headerRereshing)];
    // #warning 自动刷新(一进入程序就下拉刷新)
    [self.collectionView headerBeginRefreshing];
    
    //2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    if ([self.collectionArray count] < 100) {
        [self.collectionView addFooterWithTarget:self action:@selector(footerRereshing)];
    }
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.collectionView.headerPullToRefreshText = @"下拉可以刷新了";
    self.collectionView.headerReleaseToRefreshText = @"松开立即刷新了";
    self.collectionView.headerRefreshingText = @"正在刷新中";
    
    self.collectionView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.collectionView.footerReleaseToRefreshText = @"松开立即加载更多数据";
    self.collectionView.footerRefreshingText = @"正在加载中";
}

- (void)headerRereshing
{
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        [self.collectionView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.collectionView headerEndRefreshing];
    });
}


- (void)footerRereshing
{
    if ([self.collectionArray count] > 100) {
        [self.collectionView footerEndRefreshing];
    } else {
        //        self.urlModel.page += 1;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=music&condition=hot&device=iPhone&page=%ld", (long)_page];
            NSString *str1 = @"&per_page=20&status=0&tag_name=%E5%8D%8E%E8%AF%AD%7C%E7%B2%A4%E8%AF%AD";
            str = [NSString stringWithFormat:@"%@%@", str, str1];
            [self startJson:str];
            _page ++;
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.collectionView footerEndRefreshing];
        });
        
    }
    
}

- (void)startJson:(NSString *)urlStr
{
    [ConnectModel connectModelWithUrlStr:urlStr parmaters:nil finished:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *array = [dic objectForKey:@"list"];
        for (NSDictionary *dic1 in array) {
            NSNumber *ID = [dic1 objectForKey:@"id"];
            MusicListModel *model = [[MusicListModel alloc] init];
            model.ID = ID;
            [model setValuesForKeysWithDictionary:dic1];
            [self.collectionArray addObject:model];
            [model release];
        }
        [_collectionView reloadData];
    }];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
